#!/bin/bash

echo "🧪 测试node-sass修复方案..."

# 创建测试项目目录
mkdir -p test-node-sass-project
cd test-node-sass-project

# 创建package.json
cat > package.json << 'EOF'
{
  "name": "test-node-sass-project",
  "version": "1.0.0",
  "scripts": {
    "build:mp-weixin": "echo '构建微信小程序' && mkdir -p dist/build/mp-weixin && echo 'test' > dist/build/mp-weixin/test.js"
  },
  "dependencies": {
    "node-sass": "^4.14.1",
    "sass-loader": "^8.0.0"
  },
  "devDependencies": {
    "webpack": "^4.46.0"
  }
}
EOF

# 创建测试Dockerfile
cat > Dockerfile.test << 'EOF'
FROM node:14.21.3-alpine

WORKDIR /app

# 安装系统依赖
RUN apk add --no-cache \
    python3 \
    make \
    g++ \
    git \
    libc6-compat \
    linux-headers

# 设置环境变量
ENV PYTHON=/usr/bin/python3
ENV PYTHONPATH=/usr/bin/python3
ENV SASS_BINARY_SITE=https://npmmirror.com/mirrors/node-sass/
ENV NODE_SASS_SKIP_SASS_BINARY_DOWNLOAD_FOR_CI=1
ENV NODE_SASS_FORCE_BINARY=1

# 配置npm
RUN npm config set registry https://registry.npmmirror.com/
RUN npm config set sass_binary_site https://npmmirror.com/mirrors/node-sass/

# 创建.npmrc
RUN echo "registry=https://registry.npmmirror.com/" > .npmrc
RUN echo "sass_binary_site=https://npmmirror.com/mirrors/node-sass/" >> .npmrc

# 复制package.json
COPY package.json ./

# 测试node-sass安装
RUN echo "测试node-sass安装..."
RUN npm install --legacy-peer-deps --force --ignore-optional --ignore-engines

# 验证node-sass是否正常工作
RUN echo "验证node-sass..."
RUN node -e "console.log('node-sass版本:', require('node-sass').info)"

# 构建测试
RUN npm run build:mp-weixin

# 检查输出
RUN echo "检查构建输出:"
RUN ls -la dist/build/mp-weixin/

CMD ["tail", "-f", "/dev/null"]
EOF

echo "✅ 创建了测试项目"
echo "🔧 构建测试Docker镜像..."
docker build -f Dockerfile.test -t test-node-sass-fix .

if [ $? -eq 0 ]; then
    echo "✅ Docker构建成功！"
    echo "🔍 进入容器验证..."
    docker run -it --rm test-node-sass-fix sh -c "
        echo '验证node-sass安装:'
        node -e \"console.log('node-sass版本:', require('node-sass').info)\"
        echo ''
        echo '检查构建输出:'
        ls -la dist/build/mp-weixin/
    "
else
    echo "❌ Docker构建失败"
fi

# 清理
cd ..
rm -rf test-node-sass-project
